import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
import dataInfo from "./src/part/dataInfo.json";
import { existsSync } from "fs";
import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";

// 组件名称和输出目录配置
const componentName = dataInfo.name;
if (!componentName) {
  throw new Error("dataInfo.json 中未定义组件名称 (name)");
}

const distRoot = resolve(__dirname, "dist");

export default defineConfig({
  plugins: [
    vue(),
    cssInjectedByJsPlugin(), // ✅ 注入 CSS 到 JS
    {
      name: "replace-vue-imports",
      apply: "build", // 只在打包生效
      enforce: "post", // 在 Vue 插件之后
      generateBundle(options, bundle) {
        for (const fileName in bundle) {
          const chunk = bundle[fileName];
          if (chunk.type === "chunk") {
            chunk.code = chunk.code.replace(
              /import\s*{\s*([^}]*)\s*}\s*from\s*['"]vue['"];/g,
              (_, apiList) => {
                // 处理 'as' 语法，将 'something as mySomething' 转换为 'mySomething: something'
                const apis = apiList
                  .split(",")
                  .map((v) => v.trim())
                  .map((item) => {
                    // 将 'something as mySomething' 转换为 'mySomething: something'
                    return item.replace(/\s+as\s+/g, ": ");
                  })
                  .join(", ");

                return `const { ${apis} } = window.VueGlobal;`;
              }
            );
          }
        }
      },
    },
  ],
  define: {
    "process.env": {},
  },
  publicDir: false,
  build: {
    outDir: distRoot,
    emptyOutDir: false,
    lib: {
      entry: resolve(__dirname, "src/part/attr.vue"), // 直接用 vue 文件作为入口
      name: componentName + "Attr",
      fileName: (format) => `${componentName}/${componentName}Attr.js`,
      formats: ["es"], // 只打 ESM
    },
    sourcemap: false, // 生产模式不生成 sourcemap
    rollupOptions: {
      external: ["vue"],
      output: {
        inlineDynamicImports: true,
        globals: {
          vue: "Vue",
          // "element-plus": "ElementPlus",
        },
      },
    },
    target: "esnext", // 保持 ESM 兼容浏览器
    minify: false, // 开发或调试时可关闭压缩，方便排查
    cssCodeSplit: false, // 和插件一起配合
  },
});
